<?php
/**
 * Created by PhpStorm.
 * User: apple
 * Date: 2018/11/23
 * Time: 10:25 AM
 */

namespace app\shop\controller;

use app\shop\model\Goods as GoodsModel;
use app\shop\model\GoodsSku as GoodsSkuModel;
use think\Exception;
use think\Loader;
use think\Request;

class Goods extends \PurchaseController
{

    public function test($a, $b)
    {
//        $key = $this->generateKey();
//        p($key);

        p([$a, $b, ]);
    }


    /**
     * 获取商品列表
     * @OA\Get(tags={"Goods"}, path="/shop/goods/page", summary="商品分页列表",
     *   @OA\Parameter(name="currentPage", description="当前页 默认1", in="query", @OA\Schema(type="integer"), ),
     *   @OA\Parameter(name="pageSize", description="每页显示商品数量 默认20", in="query", @OA\Schema(type="integer"), ),
     *   @OA\Response(response="200", description="请求成功，返回商品列表",
     *     @OA\JsonContent(type="array", @OA\Items(ref="#/components/schemas/Goods")),
     *   ),
     * )
     */
    public function page()
    {
        $currentPage = input('get.currentPage', 1, 'intval');
        $pageSize = input('get.pageSize', 20, 'intval');

        $_pageFirst = ($currentPage - 1) * $pageSize;
        $_totalNum = $this->_total();

        $goodsIds = GoodsSkuModel::where([
            'is_delete' => 0,
        ])->order('sort_order', 'desc')
            ->limit($_pageFirst, $pageSize)
            ->column('goods_id');

        $this->successTerminate([
            'totalNum' => $_totalNum,
            'list' => $this->goodsList($goodsIds),
        ]);
    }

    protected function goodsList(array $goodsIds)
    {
        $result = array_map(function($goodsId) {
            return $this->_info($goodsId, true);
        }, $goodsIds);
        return $result;
    }

    protected function _total($flush = false)
    {
        return $this->cacheFirst(\CacheKey::GOODS_TOTAL_NUM, function(){
            return GoodsSkuModel::where([
                'is_delete' => 0,
                'is_on_sale' => 1,
            ])->count('goods_id');

        }, $flush);
    }


    /**
     * @OA\Get(tags={"Goods"}, path="/shop/goods/info", summary="商品详情",
     *   @OA\Parameter(name="goodsId", description="商品ID", in="query", required=true, @OA\Schema(type="integer"), ),
     *   @OA\Response(response="200", description="请求成功，返回商品详细信息", @OA\JsonContent(ref="#/components/schemas/Goods"), ),
     * )
     */
    public function info()
    {
        $goodsId = input('get.goodsId', 0, 'intval');
        /* @var $validate \app\shop\validate\Goods */
        $validate = Loader::validate('Goods');
        if (! $validate->scene('info')->check([
            'goods_id' => $goodsId,
        ])) {
            return $validate->getError();
        }

        try {
            $this->successTerminate($this->_info($goodsId, true));
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }

    protected function _info($skuId, $flush = false)
    {
        return $this->cacheFirst(\CacheKey::goodsInfo($skuId), function($skuId) {
            $goodsSkuModel = new GoodsSkuModel();
            /** @var $goods GoodsSkuModel */
            $goods = $goodsSkuModel->relation('brand,category,goods,units,specs,specs.values')
                ->field('sku_id, brand_id, cate_id, goods_id')
                ->where([
                    'sku_id' => $skuId,
                    'is_delete' => 0,
                ])->find();
//            dump($goods);
//            return $goods;
            return $goods->doWithSpecs();
        }, $flush, $skuId);
    }

    /**
     * 添加商品
     * @param Request $request
     */
    public function save(Request $request)
    {
        $this->successTerminate($request->post());
    }

    /**
     * 上传图片
     * @return \think\response\Json
     */
    public function uploadImage()
    {
        // 获取表单上传文件
        $file = request()->file('image');

        /* @var $file \Think\File */
        $info = $file->validate([
            'size' => 1024 * 1024 * 2,
            'ext' => 'jpg,jpeg,png',
        ])->move(GOODS_IMAGE_SAVE_PATH);

        if ($info) {
            // 成功上传后 获取上传信息
            // 输出 jpg
//            echo $info->getExtension();
            // 输出 42a79759f284b767dfcb2a0197904287.jpg
//            echo $info->getFilename();

//            $images[] = $info->getSaveName();
            $this->successTerminate(GOODS_IMAGE_URL . $info->getSaveName());
        } else {
            // 上传失败获取错误信息
            $this->serverErrorTerminate($file->getError());
        }
    }
}